package com.atguigu.chapter11.function;

import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/6/21 9:32
 */
public class Flink01_Function_Scala {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        DataStreamSource<String> stream = env.fromElements("hello", "atguigu", "Hello");
        
        Table table = tEnv.fromDataStream(stream, $("word"));
        
        // 1. table API中使用
        // 1.1 使用内联方式
        /*table
            .select($("word"), call(MyUpperCase.class, $("word")))
            .execute()
            .print();*/
        
        // 1.2 注册之后使用
        /*tEnv.createTemporaryFunction("my_upper", MyUpperCase.class);
        table
            .select($("word"), call("my_upper", $("word")))
            .execute()
            .print();*/
        
        // 2. 在sql中使用
        tEnv.createTemporaryFunction("myconcat", MyConcat.class);  // 在sql中使用的时候, 必须先注册
        tEnv.sqlQuery("select word, myconcat(word, '10') from " + table).execute().print();
        
    }
    
    public static class MyUpperCase extends ScalarFunction {
        public String eval(String s) {
            if (s != null) {
                return s.toUpperCase();
            }
            return null;
            
        }
    }
    
    public static class MyConcat extends ScalarFunction {
        public String eval(String ... s) {
            StringBuilder sb = new StringBuilder();
            for (String o : s) {
                sb.append(o);
            }
            return sb.toString();
        }
    }
    
}

